package cn.client.ui.view.main.chat.friendApply

import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.wrapContentHeight
import androidx.compose.foundation.layout.wrapContentWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.MoreVert
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.ComposeCompilerApi
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.R
import cn.client.data.remoteData.bean.FriendCardItem
import cn.client.data.remoteData.bean.ReceiveFriendApply
import coil.compose.AsyncImage

@Composable
fun FriendApplyPage(
    userId: Int,
    navController: NavController,
    viewModel: FriendApplyViewModel = hiltViewModel()
){
    val context = LocalContext.current
    // 使用 collectAsState 来观察 ViewModel 中的 friendApplies 状态
    val friendAppliesState = viewModel.friendApplies.collectAsState(initial = emptyList())
    val receiveFriendApplies = friendAppliesState.value


    viewModel.dispatch(FriendApplyViewModel.PageIntent.ReceiveFriendApply(uid = userId))

    LaunchedEffect(Unit) {
        viewModel.pageEvents.collect {
            when (it) {
                is FriendApplyViewModel.PageEvent.ReceiveFriendApplies -> {
                    Toast.makeText(context, "提示：查询成功", Toast.LENGTH_SHORT).show()
                }
                is FriendApplyViewModel.PageEvent.Error -> {
                    Toast.makeText(context, "提示：${it.error}", Toast.LENGTH_SHORT).show()
                }
                else -> {}
            }
        }
    }

    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
    ){

        FriendApplyTopBar(
            onClickFriendApplyTopBar = {
                navController.navigateUp()
            }
        )
        Spacer(modifier = Modifier.fillMaxWidth().height(10.dp))
        LazyColumn(
            modifier = Modifier.fillMaxSize()
        ) {
            items(receiveFriendApplies){friendApply->
                FriendApplyItem(
                    friendApply = friendApply,
                    agreeFriendApply = object: AgreeFriendApplyClickListener{
                        override fun onAgreeClicked(uid: Int, target: Int){
                            // 发送意图
                            viewModel.dispatch(FriendApplyViewModel.PageIntent.AgreeFriendApply(uid, target))
                        }
                    },
                    ignoreFriendApply = object: IgnoreFriendApplyClickListener{
                        override fun onIgnoreClicked(uid: Int, target: Int){
                            // 发送意图
                            viewModel.dispatch(FriendApplyViewModel.PageIntent.IgnoreFriendApply(uid, target))
                        }
                    }
                )
            }
        }
    }
}

// 用于同意好友申请
interface AgreeFriendApplyClickListener {
    fun onAgreeClicked(uid: Int, target: Int)
}

// 用于忽略好友申请
interface IgnoreFriendApplyClickListener {
    fun onIgnoreClicked(uid: Int, target: Int)
}


@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun FriendApplyTopBar(
    onClickFriendApplyTopBar: () -> Unit
){

    TopAppBar(
        colors = TopAppBarDefaults.topAppBarColors(
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            titleContentColor = MaterialTheme.colorScheme.primary
        ),
        title = { Text("好友申请") },
        /* 左边按钮 */
        navigationIcon = {
            IconButton(onClick = {
                onClickFriendApplyTopBar()
            }) {
                Icon(Icons.AutoMirrored.Filled.ArrowBack, null)
            }
        },
        /* 右边按钮（可以是多个） */
        actions = {
            IconButton(onClick = {  }
            ) { Icon(Icons.Filled.MoreVert, null) }
        })
}

// 好友申请单项
@Composable
fun FriendApplyItem(
    friendApply: ReceiveFriendApply,
    agreeFriendApply: AgreeFriendApplyClickListener,
    ignoreFriendApply: IgnoreFriendApplyClickListener
){
    var isExpanded by remember { mutableStateOf(false) }

    Row(
        modifier = Modifier
            .fillMaxWidth()
    ){
        /* 申请好友的信息 */
        // 头像
        Row(
            modifier = Modifier
                .padding(5.dp)
                .clickable { /* TODO: */ }
        ) {
            AsyncImage(
                model = friendApply.avatar,
                contentDescription = null,
                contentScale = ContentScale.Crop,
                modifier = Modifier
                    .size(55.dp)
                    .clip(CircleShape)
            )
        }
        Column(
            modifier = Modifier.fillMaxWidth(0.65f)
        ) {
            /* 用户名 */
            Row(
                modifier = Modifier.padding(2.dp)
            ){
                Text(text = "用 户：${friendApply.nickname}", fontSize = 16.sp)
            }
            /* 验证消息 */
            Row(
                modifier = Modifier
                    .padding(2.dp)
                    .clickable { isExpanded = !isExpanded }
            ){
                Text(text = "验证消息：${friendApply.applyInfo}", color = Color.DarkGray, maxLines = if (isExpanded) Int.MAX_VALUE else 1 )
            }
        }
        /* 按钮：同意和忽略 */
        Row(
            modifier = Modifier.wrapContentWidth()
        ){
            TextButton(onClick = {
            /* 发送同意好友申请的意图 */
                agreeFriendApply.onAgreeClicked(uid = friendApply.uid, target = friendApply.fid)
            }) {
                Text(text = "同意")
            }
            TextButton(onClick = {
                /* 发送忽略好友申请的意图 */
                ignoreFriendApply.onIgnoreClicked(uid = friendApply.uid, target = friendApply.fid)
            }) {
                Text(text = "忽略", color = Color.Gray)
            }
        }
    }
}


